#include "PlainTexture.h"
#include "GLTexture2D.h"
#include "GameObject.h"
#include "Scene.h"
#include "Transformation.h"
#include "Camera.h"
#include "TextureManager.h"
#include "Exception.h"

using namespace game_engine;
using namespace game_engine::components;
using namespace game_engine::open_gl;
using namespace game_engine::utils;

///////////////////////////////////////////////////////////////////////////////
// Constructors and Destructors
///////////////////////////////////////////////////////////////////////////////

PlainTexture::PlainTexture(void)
    : Component(), textureFile(), textureType(), hudElement(false)
{
    type = "PlainTexture";
}

PlainTexture::PlainTexture(GameObject *obj, const string &file, const INT32 t,
                           const BOOL hud)
    : Component(obj), textureFile(file), textureType(t), hudElement(hud)
{
    type = "PlainTexture";
}

PlainTexture::~PlainTexture(void)
{
}

///////////////////////////////////////////////////////////////////////////////
// Other public methods
///////////////////////////////////////////////////////////////////////////////

void PlainTexture::initialize(void) throw(...)
{
    TextureManager *tm = TextureManager::getInstance();
    tm->setTexture(textureFile, textureType);    
}

void PlainTexture::render(void) throw(...)
{
    // Retrive the Transformation component
    Transformation *transf;
    try
    {
        transf = dynamic_cast<Transformation*> 
            (object->getComponent("Transformation"));
    } catch (...)
    {
        string msg("[PlainTexture::render] transformation component not found");
        throw RuntimeException(msg);
    }

    // Retrieve texture from TextureManager
    TextureManager *tm = TextureManager::getInstance();
    GLTexture2D texture = tm->getTexture(textureFile);

    // If the texture is part of the game's HUD
    if (hudElement)
    {
        texture.drawAtPoint(transf->getPosition());
    }
    else
    {
        // Calculate offset according to camera position
        Point offset = computeCameraOffset();

        // Draw texture at object's position
        Point drawPoint(offset.getX() + transf->getXPosition(),
            offset.getY() + transf->getYPosition());
        texture.drawAtPoint(drawPoint);
    }
}

///////////////////////////////////////////////////////////////////////////////
// Getters
///////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////
// Setters
///////////////////////////////////////////////////////////////////////////////

void PlainTexture::setTextureFile(const string &file)
{
    textureFile = file;
}

void PlainTexture::setTextureType(const INT32 type)
{
    textureType = type;
}
